package com.soft.line.service.impl;

import com.soft.line.common.AppletSystemConstant;
import com.soft.line.entity.AppletCertificate;
import com.soft.line.entity.AttachmentInfo;
import com.soft.line.mapper.AppletCertificateMapper;
import com.soft.line.mapper.AppletCommonMapper;
import com.soft.line.service.AppletCertificateService;
import com.soft.line.util.MP.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 小程序 证书
 *
 * @author wpb
 * @version 1.0
 * @date 2020/6/3 15:45
 */
@Service
public class AppletCertificateServiceImpl implements AppletCertificateService {

    /**
     * 虚拟
     */
    @Value("${uploadFileMapping}")
    private String uploadFileMappingUrl;

    /**
     * 文件上传路径  例如：D盘下的路径
     */
    @Value(value = "${uploadFileDir}")
    private String uploadFileDir;

    @Autowired
    private AppletCertificateMapper appletCertificateMapper;

    @Autowired
    private AppletCommonMapper appletCommonMapper;

    @Override
    public AjaxResult getCertificateNum() {
        Map<String, Object> map = new HashMap<>(0);
        List<Map<String, Object>> mapList = appletCertificateMapper.getCertificateNum();
        //查询证书类型
        List<String> certTypes = appletCommonMapper.codeDetailList(AppletSystemConstant.CODE_TYPE_CERT);

        if (certTypes.size() > 0) {
            for (String certType : certTypes) {
                map.put(certType, 0);
            }

            for (Map<String, Object> mapData : mapList) {
                for (String certType : certTypes) {
                    if (certType.equals(mapData.get("certType"))) {
                        map.put(certType, mapData.get("num"));
                    }
                }
            }

        } else {
            return AjaxResult.error("查询证书类型出错");
        }
        return AjaxResult.success(map);
    }

    @Override
    public AjaxResult getCertificateYearList(Map<String, Object> paramMap) {
        List<Map<String, Object>> list = new ArrayList<>();

        //获取今年字符串 例：2020
        String year = getDate("yyyy", new Date());

        for (int i = Integer.parseInt(year); i > AppletSystemConstant.ASSIGN_YEAR; i--) {
            Map<String, Object> map = new HashMap<>(0);
            map.put("beginDate", String.valueOf(i));
            map.put("num", AppletSystemConstant.NUM);
            list.add(map);
        }

        // beginDate = 0  ;  2005年以前
        Map<String, Object> map = new HashMap<>(0);
        map.put("beginDate", AppletSystemConstant.NUM);
        map.put("num", AppletSystemConstant.NUM);
        list.add(map);

        List<Map<String, Object>> mapList = appletCertificateMapper.getCertificateYearList(paramMap.get("certType").toString());

        if (mapList.size() > 0) {
            //2005 年之前的，不包含2005
            int num = 0;
            int time = 2005;
            for (Map<String, Object> mapYear : mapList) {
                if (Integer.parseInt(mapYear.get("beginDate").toString()) < time) {
                    num += Integer.parseInt(mapYear.get("num").toString());
                }

                //数据处理  2005年 以后的
                for (Map<String, Object> mapLists : list) {
                    for (Map<String, Object> mapData : mapList) {
                        if (Integer.parseInt(mapLists.get("beginDate").toString()) != 0) {
                            if (mapLists.get("beginDate").equals(mapData.get("beginDate"))) {
                                mapLists.put("num", mapData.get("num"));
                            }
                        } else {
                            mapLists.put("num", num);
                        }
                    }
                }

            }
        }

        return AjaxResult.success(list);
    }

    @Override
    public AjaxResult getCertificateList(Map<String, Object> paramMap) {
        Map<String, Object> map = new HashMap<>(0);

        //从第几条开始
        int num = ((Integer.parseInt(paramMap.get("pageNum").toString())) - 1) * (Integer.parseInt(paramMap.get("dataNum").toString()));
        paramMap.put("pageNum", num);

        List<Map<String, Object>> mapList = appletCertificateMapper.getCertificateList(paramMap);

        //条件下的总个数
        //int i = appletCertificateMapper.countCertificateList(paramMap);
        int i = mapList.size();

        //总个数大于
        map.put("hasMore", i > (num + ((int) paramMap.get("dataNum"))));
        map.put("certificateList", mapList);

        return AjaxResult.success(map);
    }

    @Override
    public AjaxResult getCertificate(Map<String, Object> paramMap) {
        //证书详情
        Map<String, Object> certificate = appletCertificateMapper.getCertificate(paramMap);

        if (certificate == null || certificate.isEmpty()) {
            return AjaxResult.error("未查询出结果");
        }

        //如果值为null 转化为""
        for (String key: certificate.keySet()) {
            if (certificate.get(key)==null){
                certificate.put(key,"");
            }
        }

        //附件详情
        List<Map<String, Object>> attachmentList = appletCommonMapper.getAnnexes(Integer.parseInt(paramMap.get("id").toString()), "2");
        //拼接路径
        List<Map<String, Object>> annexesList = new ArrayList<>();
        // 拼 路径 uploadFileMappingUrl
        for (Map<String, Object> mapAnnex : attachmentList) {
            mapAnnex.put("attachmentUrl", uploadFileMappingUrl + mapAnnex.get("attachmentUrl"));
            annexesList.add(mapAnnex);
        }

        certificate.put("attachmentList", annexesList);

        return AjaxResult.success(certificate);
    }

    @Override
    public AjaxResult updateCertificate(AppletCertificate appletCertificate) {
        if (appletCertificateMapper.checkCertificateByCertIdAndId(appletCertificate.getCertId(),appletCertificate.getId ()) != 0) {
            return AjaxResult.error("证书编号已存在");
        }

        if (appletCertificateMapper.updateCertificate(appletCertificate) != 1) {
            return AjaxResult.error("修改证书失败");
        }

        List<AttachmentInfo> deleteAttachmentList = appletCertificate.getDeleteAttachmentList();

        StringBuilder deleteErrorMsg = new StringBuilder();

        if (deleteAttachmentList.size() > 0) {

            //执行删除
            for (AttachmentInfo attachmentInfo : deleteAttachmentList) {
                //附件表 url
                String attachmentUrl = attachmentInfo.getAttachmentUrl();
                String fileUrl = attachmentUrl.substring(attachmentUrl.indexOf(uploadFileMappingUrl) + 12);

                //删除附件文件
                File fileDir = new File(uploadFileDir + fileUrl);
                boolean deleteResult = fileDir.delete();

                if (!deleteResult) {
                    //deleteErrorMsg += "，删除文件：" + attachmentUrl.substring(attachmentUrl.lastIndexOf("/")) + "失败";
                    deleteErrorMsg.append("，删除文件：").append(attachmentUrl.substring(attachmentUrl.lastIndexOf("/")+1)).append("失败");
                } else {
                    appletCommonMapper.delAnnex(attachmentInfo.getId());
                }

            }
        }

        return AjaxResult.success("修改证书成功" + deleteErrorMsg);
    }

    @Override
    public AjaxResult deleteCertificate(Map<String, Object> paramMap) {
        //删除时间
        paramMap.put("modifyTime", new Date());
        //删除状态
        paramMap.put("delFlg", "1");
        if (appletCertificateMapper.deleteCertificate(paramMap) != 1) {
            return AjaxResult.error("删除合同失败");
        } else {
            //附件信息
            List<Map<String, Object>> oldAttachments = appletCommonMapper.getAnnexes((int) paramMap.get("id"), "2");

            //删除附件
            for (Map<String, Object> map : oldAttachments) {
                //附件表 url
                String attachmentUrl = (String) map.get("attachmentUrl");

                //删除附件文件
                File fileDir = new File(uploadFileDir + attachmentUrl);

                boolean deleteResult = fileDir.delete();

                //删除附件基本信息
                if (deleteResult) {
                    appletCommonMapper.delAnnex((int) map.get("id"));
                }
            }

            return AjaxResult.success();
        }
    }

    @Override
    public AjaxResult getCertificateSearchList(Map<String, Object> paramMap) {
        Map<String,Object> map = new HashMap<>(0);

        //从第几条开始
        int num = ((int) paramMap.get("pageNum") - 1) * ((int) paramMap.get("dataNum"));
        paramMap.put("pageNum", num);

        List<Map<String,Object>> mapList = appletCertificateMapper.getCertificateSearchList(paramMap);

        map.put("certificateList",mapList);
        //条件下的总个数
        map.put("hasMore",appletCertificateMapper.countGetCertificateSearchList(paramMap) > (num+(int) paramMap.get(AppletSystemConstant.DATA_NUM)) );

        return AjaxResult.success(map);
    }

    @Override
    public AjaxResult addCertificate(AppletCertificate appletCertificate) {

        if (appletCertificateMapper.checkCertificateByCertId(appletCertificate.getCertId()) != 0) {
            return AjaxResult.error("证书编号已存在");
        }

        if(appletCertificateMapper.addCertificate(appletCertificate) == 1){
            Map<String,Object> map = new HashMap<>(0);
            map.put("id",appletCertificate.getId());
            return AjaxResult.success(map);
        }
        return AjaxResult.error();
    }

    @Override
    public AjaxResult getCertificateQueryList(Map<String, Object> paramMap) {
        Map<String,Object> map = new HashMap<>(0);

        //从第几条开始
        int num = ((int) paramMap.get("pageNum") - 1) * ((int) paramMap.get("dataNum"));
        paramMap.put("pageNum", num);

        List<Map<String,Object>> mapList = appletCertificateMapper.getContractQueryList(paramMap);

        map.put("certificateList",mapList);
        map.put("hasMore",appletCertificateMapper.countGetContractQueryList(paramMap) > (num+(int) paramMap.get(AppletSystemConstant.DATA_NUM)) );

        return AjaxResult.success(map);
    }

    /**
     * 自定义时间格式
     *
     * @param timeFormat 格式化
     * @param date       日期
     * @return
     */
    public static String getDate(String timeFormat, Date date) {
        DateFormat dateFormat = new SimpleDateFormat(timeFormat);
        return dateFormat.format(date);
    }

}
